<template>
  <view class="container">
    <view class="top">
      <!-- 维修方式 -->
      <uni-card margin="15rpx">
        <view class="repair-type-row">
          <text class="repair-type-label">维修方式</text>
          <radio-group class="repair-type-group" @change="onRepairTypeChange">
            <label class="repair-type-option">
              <radio value="到店维修" :checked="repairReservation.type === '到店维修'" />
              <text>到店维修</text>
            </label>
            <label class="repair-type-option">
              <radio value="上门取车" :checked="repairReservation.type === '上门取车'" />
              <text>上门取车</text>
            </label>
          </radio-group>
        </view>
      </uni-card>
      <uni-card margin="15rpx" title="客户信息">
        <!-- 用户姓名 -->
        <view class="info-row">
          <text class="info-label">车主姓名</text>
          <input v-model="repairReservation.name" class="info-input" placeholder="请输入姓名" />
        </view>
        <!-- 联系方式 -->
        <view class="info-row">
          <text class="info-label">联系方式</text>
          <input v-model="repairReservation.phone" class="info-input" type="number" placeholder="请输入电话号码" />
        </view>
        <!-- 预约时间 -->
        <view class="info-row">
          <text class="info-label">预约时间</text>
          <!-- 修改 type 属性为 date -->
          <uni-datetime-picker v-model="repairReservation.reservationTime" type="date" @confirm="onConfirm"
            @cancel="onCancel" ref="datePicker">
            <input class="info-input-time" :value="repairReservation.reservationTime" placeholder="请选择预约时间"
              @click="showDatePicker" />
          </uni-datetime-picker>
        </view>
        <view v-if="repairReservation.type === '上门取车'" class="info-row">
          <text class="info-label">取车地址</text>
          <input v-model="repairReservation.location" class="info-input" placeholder="请输入取车地址" />
        </view>
      </uni-card>

      <!-- 车辆信息 -->
      <uni-card margin="15rpx" title="车辆信息">
        <!-- 车辆类型 -->
        <view class="info-row">
          <text class="info-label">车辆类型</text>
          <view class="picker-wrapper">
            <picker :range="vehicleTypes" @change="bindVehicleTypeChange">
              <!-- 修改绑定值为选中的车辆类型文字 -->
              <input class="info-input has-icon" :value="vehicleTypes[vehicleTypeIndex]" placeholder="请选择车辆类型" />
            </picker>
          </view>
        </view>
        <!-- 车牌号 -->
        <view class="info-row">
          <text class="info-label">车牌号</text>
          <input v-model="repairReservation.carNum" class="info-input" placeholder="请输入车牌号" />
        </view>
      </uni-card>
      <uni-card margin="15rpx" title="图片">
        <view class="">
          <text class="image-title">整车照片：</text>
          <uni-section>
            <view class="example-body">
              <!-- 添加 @select 事件处理 -->
              <uni-file-picker limit="9" @select="onWholeCarImageSelect"></uni-file-picker>
            </view>
          </uni-section>
        </view>
        <view class="">
          <text class="image-title">维修部位照片：</text>
          <uni-section>
            <view class="example-body">
              <!-- 添加 @select 事件处理 -->
              <uni-file-picker limit="9" @select="onRepairPartImageSelect"></uni-file-picker>
            </view>
          </uni-section>
        </view>
      </uni-card>
      <!-- 底部按钮 -->
      <view class="bottom-btns">
        <button class="reserve-btn" @click="submitReservation">
          提交
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import request from '@/untils/request.js'
import baseUrl from '@/untils/urlConfig.js'

// 定义一个对象来存储所有预约信息
const repairReservation = ref({
  type: '到店维修', // 维修类型
  name: '', // 车主姓名
  phone: '', // 联系方式
  reservationTime: '', // 预约时间
  location: '', // 取车地址
  carTypeId: '', // 车辆类型
  carNum: '', // 车牌号
  // oos处理后的图片
  vehiclePhotos: '', // 整车照片
  repairPhotos: ''// 维修部位照片
});


// 车辆类型数组
const vehicleTypes = ref(['请选择车辆类型', '轿车', 'SUV', 'MPV', '跑车', '皮卡', '旅行车', '越野', '微面'])

// 车辆类型映射对象
const vehicleTypeMap = {
  '请选择车辆类型': -1, // 修改映射值为 -1
  '轿车': 1,
  'SUV': 2,
  'MPV': 3,
  '跑车': 4,
  '皮卡': 5,
  '旅行车': 6,
  '越野': 7,
  '微面': 8
}

// 车辆类型选中的索引
const vehicleTypeIndex = ref(0)

// 车辆类型选择改变的回调
const bindVehicleTypeChange = (e) => {
  vehicleTypeIndex.value = e.detail.value
  const selectedType = vehicleTypes.value[vehicleTypeIndex.value]
  repairReservation.value.carTypeId = vehicleTypeMap[selectedType]
}


// 处理整车照片选择事件
const onWholeCarImageSelect = async (e) => {
  try {
    // 先从缓存中获取 token
    // let token = uni.getStorageSync('token');
    // 如果缓存中没有 token，则使用临时 token
    let token = 'eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6ImExY2Y2YzQ1LWQ3NGYtNDNhZC04Nzc2LTc5ZjVjZTYzYzJhNCIsInVzZXJuYW1lIjoiYWRtaW4ifQ.sVcpT_LwYzWmTz2keOUxQnysqcNWp6nQ7gf3vdidU5Kc4kejJck3gtAjySJDDsGQfRbTP6O-1zMGX8MnxrWfdw';
    // 检查是否有文件被选择
    if (!e.tempFiles || e.tempFiles.length === 0) {
      uni.showToast({ title: '请先选择文件', icon: 'none' });
      return;
    }

    // 上传第一个文件（如需多文件上传可用Promise.all处理多个）
    const file = e.tempFiles[0];

    uni.uploadFile({
      url: `${baseUrl}/file/upload`,
      filePath: file.path,
      name: 'file', // 后端接收的字段名
      header: {
        'Authorization': token 
        // 注意：uni.uploadFile会自动设置Content-Type，无需手动指定
      },
      formData: {
        // 可附加其他表单参数
        userId: '123'
      },
      success: (res) => {
        try {
          // 解析返回数据
          const response = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
          // console.log('上传成功:', response);

          // 存储返回的文件路径
          if (response.data?.url) {
            repairReservation.value.vehiclePhotos = response.data.url;
            uni.showToast({ title: '上传成功', icon: 'success' });
          }
        } catch (e) {
          console.error('解析响应失败:', e);
          uni.showToast({ title: '解析响应失败', icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('上传失败:', err);
        uni.showToast({
          title: '上传失败: ' + (err.errMsg || '未知错误'),
          icon: 'none'
        });
      }
    });
  } catch (error) {
    console.error('全局错误:', error);
    uni.showToast({ title: '操作失败', icon: 'none' });
  }
};

// 处理维修部位照片选择事件
const onRepairPartImageSelect = (e) => {
  try {
    // 先从缓存中获取 token
    // let token = uni.getStorageSync('token');
    // 如果缓存中没有 token，则使用临时 token
    let token = 'eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6ImExY2Y2YzQ1LWQ3NGYtNDNhZC04Nzc2LTc5ZjVjZTYzYzJhNCIsInVzZXJuYW1lIjoiYWRtaW4ifQ.sVcpT_LwYzWmTz2keOUxQnysqcNWp6nQ7gf3vdidU5Kc4kejJck3gtAjySJDDsGQfRbTP6O-1zMGX8MnxrWfdw';
    // 检查是否有文件被选择
    if (!e.tempFiles || e.tempFiles.length === 0) {
      uni.showToast({ title: '请先选择文件', icon: 'none' });
      return;
    }

    // 上传第一个文件（如需多文件上传可用Promise.all处理多个）
    const file = e.tempFiles[0];

    uni.uploadFile({
      url: `${baseUrl}/file/upload`,
      filePath: file.path,
      name: 'file', // 后端接收的字段名
      header: {
        'Authorization': token // 使用从缓存获取或临时的 token
        // 注意：uni.uploadFile会自动设置Content-Type，无需手动指定
      },
      formData: {
        // 可附加其他表单参数
        userId: '1234'
      },
      success: (res) => {
        try {
          // 解析返回数据
          const response = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
          // console.log('上传成功:', response);

          // 存储返回的文件路径
          if (response.data?.url) {
            // 如果是数组则concat，否则push
            repairReservation.value.repairPhotos = response.data.url;
            uni.showToast({ title: '上传成功', icon: 'success' });
          }
        } catch (e) {
          console.error('解析响应失败:', e);
          uni.showToast({ title: '解析响应失败', icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('上传失败:', err);
        uni.showToast({
          title: '上传失败: ' + (err.errMsg || '未知错误'),
          icon: 'none'
        });
      }
    });
  } catch (error) {
    console.error('全局错误:', error);
    uni.showToast({ title: '操作失败', icon: 'none' });
  }
}
// 确认选择时间的回调
const onConfirm = (e) => {
  reservationTime.value = e.detail.value;
};

// 取消选择时间的回调
const onCancel = () => {
  console.log('用户取消选择时间');
};

// 显示日期选择器的方法
const showDatePicker = () => {
  if (datePicker.value) {
    datePicker.value.show()
  }
}



// 维修类型变更处理
const onRepairTypeChange = (e) => {
  // Bug 修复：将值赋给正确的属性
  repairReservation.value.type = e.detail.value;
  // console.log('Repair type has been changed to:', repairReservation.value.type); // For debugging
};

// 提交预约
const submitReservation = () => {
  // 简单表单验证
  if (!repairReservation.value.name) { // 可以直接从 repairReservation 获取
    uni.showToast({
      title: '请输入车主姓名',
      icon: 'none'
    })
    return
  }

  if (!repairReservation.value.phone) {
    uni.showToast({
      title: '请输入联系方式',
      icon: 'none'
    })
    return
  }

  if (!repairReservation.value.reservationTime) {
    uni.showToast({
      title: '请选择预约时间',
      icon: 'none'
    })
    return
  }

  // Bug 修复：修正访问 repairType 的方式
  if (repairReservation.value.type === '上门取车' && !repairReservation.value.location) {
    uni.showToast({
      title: '请输入取车地址',
      icon: 'none'
    })
    return
  }

  if (vehicleTypeIndex.value === 0) {
    uni.showToast({
      title: '请选择车辆类型',
      icon: 'none'
    })
    return
  }

  if (!repairReservation.value.carNum) {
    uni.showToast({
      title: '请输入车牌号',
      icon: 'none'
    })
    return
  }

  // 所有验证通过，提交数据
  console.log('预约信息:', repairReservation.value);

  // 复制一份预约信息
  const dataToSubmit = { ...repairReservation.value };
  // 处理 vehiclePhotos
  if (Array.isArray(repairReservation.value.vehiclePhotos)) {
    dataToSubmit.vehiclePhotos = repairReservation.value.vehiclePhotos.join(',');
  } else {
    dataToSubmit.vehiclePhotos = repairReservation.value.vehiclePhotos;
  }
  // 处理 repairPhotos
  if (Array.isArray(repairReservation.value.repairPhotos)) {
    dataToSubmit.repairPhotos = repairReservation.value.repairPhotos.join(',');
  } else {
    dataToSubmit.repairPhotos = repairReservation.value.repairPhotos;
  }

  // 调用接口添加预约信息
  request({
    url: `${baseUrl}/chy/reservation`,
    method: 'POST',
    data: dataToSubmit,
    success: (res) => {
      console.log('预约成功:', res);
      uni.showToast({
        title: '预约提交成功',
        icon: 'success'
      });
      // 跳转到successfully页面
      setTimeout(() => {
        uni.navigateTo({         
          url: '/pages/autoRepair/successfully/successfully'
        });
      }, 800);
    },
  });

  // 重置表单
  repairReservation.value = {
    type: '到店维修', // 维修类型
    name: '', // 车主姓名
    phone: '', // 联系方式
    reservationTime: '', // 预约时间
    location: '', // 取车地址
    carTypeId: '', // 车辆类型
    carNum: '', // 车牌号
    vehiclePhotos: [], // 整车照片
    repairPhotos: [] // 维修部位照片
  };
  vehicleTypeIndex.value = 0;
}
</script>

<style scoped>
.container {
  background: #fff;
  min-height: 100vh;
  padding-bottom: 80rpx;
}


.top {
  margin-top: -15rpx;
  padding-top: 20rpx;
  height: 300rpx;
  background-color: #3083fb;
}


.repair-type-row {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
}


.repair-type-label {
  font-weight: bold;
  margin-right: 24rpx;
  font-size: 28rpx;
}


.repair-type-group {
  display: flex;
  align-items: center;
}


.repair-type-option {
  display: flex;
  align-items: center;
  margin-right: 50rpx;
  font-size: 28rpx;
}


.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15rpx;
}


.info-label {
  width: 150rpx;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  border-radius: 50rpx;
  background-color: #3083fb;
  color: white;
  font-size: 28rpx;
}


.info-input {
  border: 1rpx solid #ccc;
  border-radius: 50rpx;
  padding: 10rpx 25rpx 10rpx 25rpx;
  width: 60%;
  font-size: 28rpx;
}


.info-input-time {
  margin-left: 50rpx;
  border: 1rpx solid #ccc;
  border-radius: 50rpx;
  padding: 10rpx 25rpx 10rpx 25rpx;
  width: 78%;
  font-size: 28rpx;
}


.picker-wrapper {
  margin-right: 40rpx;
}


.info-input.has-icon {
  width: 95%;
}


.upload-container {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
  margin-top: 15rpx;
}


.uploaded-image {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  border-radius: 8rpx;
  overflow: hidden;
}


.uploaded-image image {
  width: 100%;
  height: 100%;
}


.delete-btn {
  position: absolute;
  top: 0;
  right: 0;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  text-align: center;
  line-height: 40rpx;
  border-bottom-left-radius: 8rpx;
  cursor: pointer;
}


.upload-btn {
  width: 200rpx;
  height: 200rpx;
  border: 2rpx dashed #ccc;
  border-radius: 8rpx;
  font-size: 80rpx;
  color: #ccc;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}


.image-title {
  font-size: 28rpx;
  padding-top: 20rpx;
}


.bottom-btns {
  width: 100%;
  margin-top: 90rpx;
  display: flex;
  justify-content: center;
}


.reserve-btn {
  flex: 1;
  margin: 0 32rpx;
  background: #3083fb;
  color: #fff;
  border-radius: 40rpx;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}


.example-body {
  padding: 10px;
  padding-top: 0;
}
</style>
